import axios from 'axios'
import store from'../store/index'
import {Message } from 'element-ui'
import router from "../router/index"


const service = axios.create({
    baseURL:'/api',
    timeout: 50000
})

//请求拦截器
service.interceptors.request.use(
    config => {
        const token =store.getters.token
        if (token) {
            config.headers['TOKEN'] = token
        }else{
            if(router.currentRoute.fullPath!='/login'){
                Message.warning("您还未登录,请先登录~")
                router.push("/login")
            }
        }
        return config
    },
    error =>Promise.reject(error)

)


service.interceptors.response.use(

    response => {
        const res = response
        const {code}=res.data
        if (code==100) {
            return res;
        }else if(code==110){
            Message.warning(res.data.msg)
            router.push("/login")
        }else if(code>100&&code<1000){
            const {data}=response
            const msg=data.msg
            Message.warning(msg)
            if(data.code==360){
                return  res;
            }
        }
    },
    error => {
        let msg=[]
        for(let item of error.data.errors){
            msg.push(item.defaultMessage);
        }
        console.log('err' + error) // for debug
        Message.warning(msg);
        return Promise.reject(error)
    }
)

export default service
